/*
 * jquery.uploadProgress
 *
 * Copyright (c) 2008 Piotr Sarnacki (drogomir.com)
 * 2012 Completely modified by Pascal Beyeler (removed unnecessary stuff) 
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
(function($) {

	jQuery.uploadProgress = function(options) {

		options = $.extend({
			dataType : "json",
			interval : 2000,
			progressUrl : "/progress",
			start : function() {
			},
			uploading : function() {
			},
			complete : function() {
			},
			success : function() {
			},
			error : function() {
			},
			timer : ""
		}, options);

		options.timer = window.setInterval(function() {
			jQuery.ajax({
				type : "GET",
				cache : false,
				url : options.progressUrl + "?X-Progress-ID=" + options.uuid,
				dataType : options.dataType,
				headers : {
					'X-Progress-ID': options.uuid
				},
				success : function(upload) {
					if(!upload) {
						return;
					}
					if (upload) {
						if (upload.state == 'uploading') {
							upload.percents = Math.floor((upload.received / upload.size) * 1000) / 10;
							options.uploading(upload);
						}

						if (upload.state == 'done' || upload.state == 'error') {
							upload.percents = 100;
							window.clearTimeout(options.timer);
							options.complete(upload);
						}

						if (upload.state == 'done') {
							options.success(upload);
						}

						if (upload.state == 'error') {
							options.error(upload);
						}

						if (upload.percents) {
							var bar = $.browser.safari ? $(options.progressBar, parent.document) : $(options.progressBar);
							bar.css({
								width : upload.percents + '%'
							});
						}
					}
				}
			});

		}, options.interval);

	};

})(jQuery);